package cn.bdqn.controller;

import cn.bdqn.dto.Dto;
import cn.bdqn.pojo.*;
import cn.bdqn.service.HotelService;
import cn.bdqn.service.ItripHotelOrderService;
import cn.bdqn.service.ItripHotelRoomService;
import cn.bdqn.service.ItripOrderMessageService;
import cn.bdqn.util.MD5Utils;
import cn.bdqn.util.SystemConfig;
import cn.bdqn.vo.ItripOrderVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class ItripOrderAddController {
@Resource
private ItripHotelOrderService itripHotelOrderService;
    @Resource
    private HotelService hotelService;
    @Resource
    private SystemConfig systemConfig;
    @Resource
    private ItripOrderMessageService itripOrderMessageService;

    /**
     *添加订单
     * @param
     * @return
     */
    @ApiOperation(value = "添加订单详情", httpMethod = "POST",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "通过酒店Id获得图片")
    @RequestMapping(value = "/api/hotelorder/addhotelorder", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto addOrderMessage(@RequestBody ItripOrderVO itripOrderVO, HttpServletRequest request) throws Exception {
        Dto dto=new Dto();
        Date checkInDate= itripOrderVO.getCheckInDate();
        Date checkOutDate= itripOrderVO.getCheckOutDate();
        //需要房间数量
        Integer count=itripOrderVO.getCount();
        Long hotelId=itripOrderVO.getHotelId();
        //发票头
        String invoiceHead=itripOrderVO.getInvoiceHead();
        //发票类型
        Integer invoiceType=itripOrderVO.getInvoiceType();
        List<ItripUserLinkUser> list=itripOrderVO.getLinkUser();
        //特殊要求
        String specialRequirement=itripOrderVO.getSpecialRequirement();
        //是否需要发票
        Integer isNeedInvoice =itripOrderVO.getIsNeedInvoice();
        String noticeEmail=itripOrderVO.getNoticeEmail();
        String noticePhone=itripOrderVO.getNoticePhone();
        Integer orderType=itripOrderVO.getOrderType();
        Long roomId=itripOrderVO.getRoomId();

        String token=request.getHeader("token");
        String userId=token.split("-")[2];
        ItripHotelOrder itripHotelOrder=new ItripHotelOrder();
        itripHotelOrder.setHotelId(hotelId);
        itripHotelOrder.setCheckInDate(checkInDate);
        itripHotelOrder.setCheckOutDate(checkOutDate);
        itripHotelOrder.setUserId(Long.valueOf(userId));
        itripHotelOrder.setOrderType(orderType);
        //订单编号
        //交易编号
        //生成订单号：机器码 +日期+（MD5）（商品IDs+毫秒数+1000000的随机数）
        StringBuilder md5String = new StringBuilder();
        md5String.append(itripHotelOrder.getHotelId());
        md5String.append(itripHotelOrder.getRoomId());
        md5String.append(System.currentTimeMillis());
        md5String.append(Math.random() * 1000000);
        String md5 = MD5Utils.getMD5(md5String.toString(), 6);
        //生成订单编号
        StringBuilder orderNo = new StringBuilder();
        orderNo.append(systemConfig.getMachineCode());
        orderNo.append(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        orderNo.append(md5);
        itripHotelOrder.setOrderNo(orderNo.toString());
//        itripHotelOrder.setTradeNo("1111");
        itripHotelOrder.setHotelId(hotelId);
        //通过hotelId先查找hotelName
        ItripHotel itripHotel=hotelService.findItripHotelById(hotelId);
        itripHotelOrder.setHotelName(itripHotel.getHotelName());
        itripHotelOrder.setRoomId(roomId);
        itripHotelOrder.setCount(count);
        //计算预定天数
        int days=this.betweenStartAndEnd(checkInDate,checkOutDate).size();
        if(days<=0){
            dto.setCode("10001");
            dto.setMsg("开始日期不能小于结束日期");
            return dto;
        }
        itripHotelOrder.setBookingDays(days);
        //初始订单，未支付
        itripHotelOrder.setOrderStatus(0);

        //计算金额(roomId,count)

        itripHotelOrder.setPayAmount(itripOrderMessageService.selectrRoomMoney(count,roomId));

        //支付方式
//        itripHotelOrder.setPayType(1);
        itripHotelOrder.setNoticeEmail(noticeEmail);
        itripHotelOrder.setNoticePhone(noticePhone);
        itripHotelOrder.setIsNeedInvoice(isNeedInvoice);
        itripHotelOrder.setInvoiceHead(invoiceHead);
        itripHotelOrder.setInvoiceType(invoiceType);
        //联系人姓名
        StringBuilder linkUserName = new StringBuilder();
        int size = list.size();
        for (int i = 0; i < size; i++) {
            if (i != size - 1) {
                linkUserName.append(list.get(i).getLinkUserName() + ",");
            } else {
                linkUserName.append(list.get(i).getLinkUserName());
            }
        }
        itripHotelOrder.setLinkUserName(linkUserName.toString());
        //提交订单类型
        if (token.startsWith("token:PC")) {
            itripHotelOrder.setBookType(0);
        } else if (token.startsWith("token:MOBILE")) {
            itripHotelOrder.setBookType(1);
        } else {
            itripHotelOrder.setBookType(2);
        }
        itripHotelOrder.setCreationDate(new Date());
        itripHotelOrder.setCreatedBy(Long.valueOf(userId));
        //验证库存是否充足（roomid,count）
        Map map=new HashMap<>();
        map.put("startTime", checkInDate);
        map.put("endTime", checkOutDate);
        map.put("hotelId", hotelId);
        map.put("roomId", roomId);
        map.put("count", count);
        if(!itripHotelOrderService.selectOrderCount(map)){
            dto.setCode("10001");
            dto.setMsg("库存不足");
            return dto;
        }
        dto=itripOrderMessageService.insertOrderMessage(itripHotelOrder);

        //将联系人添加到订单用户表
//        list
        for(ItripUserLinkUser i:list){
            ItripOrderLinkUser itripOrderLinkUser=new ItripOrderLinkUser();
            itripOrderLinkUser.setLinkUserId(i.getId());
            itripOrderLinkUser.setLinkUserName(i.getLinkUserName());
            itripOrderLinkUser.setOrderId(itripHotelOrder.getId());
            itripOrderLinkUser.setCreatedBy(itripHotelOrder.getUserId());
            itripOrderLinkUser.setCreationDate(new Date());
            itripOrderMessageService.insertOrderLinkUser(itripOrderLinkUser);
        }
        return dto;
    }

    //计算两天之间的所有日期
    public List betweenStartAndEnd(Date start,Date end){
        List<Date> list=new ArrayList<>(0);
        Calendar startCal=Calendar.getInstance();
        startCal.getTime();

        Calendar endCal=Calendar.getInstance();
        endCal.getTime();
        if(startCal.before(endCal)||startCal.equals(endCal)){
            list.add(startCal.getTime());
            startCal.add(Calendar.DAY_OF_YEAR, 1);
        }
        return list;
    }
}
